package com.runchinaup.download.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.runchinaup.download.R;
import com.runchinaup.download.okhttp.NetResultUil;
import com.runchinaup.download.okhttp.ResultCallback;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

public class MainActivity extends Activity {

    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        button = findViewById(R.id.write);

        //获取网络数据和解析
        getHttpData();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //io流保存图片
                saveImage();
            }
        });


    }

    //保存图片到本地
    private void saveImage() {
        //获取app独立的地址
        String folder = Environment.getExternalStorageDirectory().getAbsolutePath();
        String shareTmpImg = "/tmps/share/";
        File dir = new File(folder + shareTmpImg);
        File file = new File(dir, System.currentTimeMillis() + ".jpg");

        if (!dir.exists()) {
            dir.mkdirs();
        }

        try {
            FileOutputStream outputStream = new FileOutputStream(file);

            Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher);
            BitmapDrawable bd = (BitmapDrawable) drawable;
            Bitmap bitmap = bd.getBitmap();
            outputStream.write(bitmap2Byte(bitmap));
            outputStream.flush();
            outputStream.close();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                }
            });

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //将图片转换成byte
    public static byte[] bitmap2Byte(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
        return baos.toByteArray();
    }

    public Bitmap getBitmipByView(View view) {
        int h = 0;
        Bitmap bitmap = null;

        h = view.getHeight();

        //创建对应大小的bitmap
        bitmap = Bitmap.createBitmap(view.getWidth(), h, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return compressImage(bitmap);
    }

    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;
        // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
        while (baos.toByteArray().length / 1024 > 300) {
            // 重置baos
            baos.reset();
            // 这里压缩options%，把压缩后的数据存放到baos中
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
            // 每次都减少10
            options -= 10;
        }
        // 把压缩后的数据baos存放到ByteArrayInputStream中
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        // 把ByteArrayInputStream数据生成图片
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }


    //获取网络数据和解析
    public void getHttpData() {
        new NetResultUil().downLoad(new ResultCallback() {
            @Override
            public void onError(Call call, IOException e) {
                Log.e("onError: ", "is error");
            }

            @Override
            public void onResponse(Response response) throws IOException {

                JsonObject jsonObject = new JsonParser().parse(response.body().string()).getAsJsonObject();

                Log.e("onResponse: json", jsonObject + "");

            }
        });
    }
}
